package com.example.studentmgt.controller;

import com.example.studentmgt.model.Student;
import com.example.studentmgt.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class StudentController {
    private final static Logger log = LoggerFactory.getLogger(StudentController.class);
    @Resource
    private StudentService studentService;

    @GetMapping("/ping")
    public String ping() {
        log.info("ping");
        return "pong";
    }

    @GetMapping("/queryAll")
    public List<Student> queryAll() {
        log.info("queryAll");
        List<Student> lists = studentService.queryAll();
        return lists;
    }

    @GetMapping("/top")
    public List<Student> top() {
        log.info("top");
        List<Student> lists = studentService.top();
        return lists;
    }

    @PostMapping("/student")
    public Student student() {
        log.info("create a student");
        return studentService.student();
    }

    @GetMapping("/findStudentById")
    public Student findStudentById(@RequestParam Long id) {
        try {
            log.info("find student by id");
            return studentService.findStudentById(id);
        } catch (Exception e) {
            log.error("find student failed: " + id);
            return null;
        }
    }

    @GetMapping("/cachedStudentById")
    public Student cachedStudentById(@RequestParam Long id) {
        try {
            log.info("find cached student by id");
            return studentService.cachedStudentById(id);
        } catch (Exception e) {
            log.error("find cached student failed: " + id);
            return null;
        }
    }

    @PostMapping("/updateStudent")
    public String updateStudent(@RequestBody Student student) {
        log.info("updateStudent");
        int result = studentService.updateStudent(student);
        if (result != 0) {
            return "update student success";
        }
        log.error("update student failed");
        return "failed";
    }

    @DeleteMapping("/deleteStudentById")
    public String deleteStudentById(@RequestParam Long id) {
        log.info("delete student by id");
        int result = studentService.deleteStudentById(id);
        if (result != 0) {
            return "delete success";
        }
        log.error("delete student failed");
        return "delete failed";
    }
}